package com.learn.project2.service.wx.cart;

import com.learn.project2.bean.*;
import com.learn.project2.mapper.*;
import com.learn.project2.model.bo.wx.cart.*;
import com.learn.project2.model.vo.wx.address.AddressListVO2;
import com.learn.project2.model.vo.wx.cart.CartCheckoutVO2;
import com.learn.project2.model.vo.wx.cart.CartIndexVO2;
import com.learn.project2.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Array;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: 尹圣淼
 * <p>
 * formatter.format(null)  ->   空指针异常
 * so  我只要遇到转换时间，就判断if null。再进行赋值
 * @Date: 2022/1/10 14:35
 */
@Service
public class CartServiceImp2 implements CartService2 {

    @Autowired
    MarketGoodsProductMapper goodsProductMapper;
    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Override
    public Result addCart(CartAddBO2 fastAddBO, Integer userId) {
        if (userId == null) {
            throw new RuntimeException("请登录后访问。");
        }
        // 先根据得到的对象进行利用
        // add 的时候  如果数据库表中有deleted =0 且遍历userid的购物车
        //  若productid等于添加的id. 则更新加1，而不是insert
        MarketCartExample marketCartExample = new MarketCartExample();
        // goodsId和productId 足以定商品的唯一属性。  不同规格就insert

        // 如果拿到的产品id为null  那么也别忙活了。直接就结束。啥也没变。 防止报错。
        if (fastAddBO.getProductId() != null && fastAddBO.getProductId() != 0) {
            marketCartExample.createCriteria().andProductIdEqualTo(fastAddBO.getProductId()).andGoodsIdEqualTo(fastAddBO.getGoodsId()).andUserIdEqualTo(userId).andDeletedEqualTo(false);
            List<MarketCart> carts = marketCartMapper.selectByExample(marketCartExample);
            // 购物车中出现两行同一完全一样的商品 ，除非通过数据库自定义添加。
            if (carts.size() == 1) {
                Integer number = fastAddBO.getNumber();
                number += carts.get(0).getNumber();
                // 购物车同种的接着进行加法即可。
                MarketCart marketCart = new MarketCart();
                marketCart.setId(carts.get(0).getId());
                marketCart.setUpdateTime(new Date());
                marketCart.setNumber(number);
                marketCartMapper.updateByPrimaryKeySelective(marketCart);
                return Result.ok(countGoods(userId));
            }


            // 新的数据： 原来没添加过。则通过insert 而非update
            MarketGoodsProduct marketGoodsProduct = goodsProductMapper.selectByPrimaryKey(fastAddBO.getProductId());
            // 库存。
            Integer stocks = marketGoodsProduct.getNumber();
            if (fastAddBO.getNumber() > stocks) {
                return Result.fail(711, "对不起，添加至购物车的数量大于商家库存:" + stocks + "，请重新选择");
            }
            MarketCart marketCart = new MarketCart();// 12个属性值。
            // 目前只是添加至购物车，并不能进入订单表，只能进入订单商品表（即购物车表）
            // 所以对表中的order_id 不予理睬。
            // 获得goodsId,specification,url,number(购买数) 赋值到订单货物表中。
            Integer goodsId = marketGoodsProduct.getGoodsId();
            marketCart.setGoodsId(goodsId); // 1
            marketCart.setPrice(marketGoodsProduct.getPrice());// 2
            String[] specifications = marketGoodsProduct.getSpecifications();
            marketCart.setSpecifications(specifications);// 3
            String url = marketGoodsProduct.getUrl();
            marketCart.setPicUrl(url);// 4
            marketCart.setNumber(fastAddBO.getNumber());// 5
            MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(fastAddBO.getGoodsId());
            marketCart.setGoodsSn(marketGoods.getGoodsSn());// 6
            marketCart.setGoodsName(marketGoods.getName());// 7
            marketCart.setAddTime(new Date());// 8
            marketCart.setUpdateTime(new Date()); // 9
            marketCart.setUserId(userId);  // 10
            marketCart.setDeleted(false); // 11
            marketCart.setChecked(false); // 12
            marketCart.setProductId(fastAddBO.getProductId()); // 13
            //  marketCart.setUserId();
            marketCartMapper.insertSelective(marketCart);
            // 只要购物车数量合理，即返回成功ok
            // 此时返回购物车的总量。
        }
        return Result.ok(countGoods(userId));
    }

    @Override
    public Integer countGoods(Integer userId) {
        if (userId == null) {
            throw new RuntimeException("请登录后访问。");
        }
        return marketCartMapper.selectCountsByUserId(userId);
    }

    @Override
    public CartIndexVO2 getIndexVO(Integer id) {
        if (id == null) {
            throw new RuntimeException("请登录后访问。");
        }
        CartIndexVO2 cartIndexVO = new CartIndexVO2();
        CartIndexVO2.CartTotalBean cartTotalBean = new CartIndexVO2.CartTotalBean();
        MarketCartExample marketCartExample = new MarketCartExample();
        // 只要有就要。（没被删除）
        marketCartExample.createCriteria().andUserIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        BigDecimal sum = new BigDecimal(0);
        Integer totalNum = 0;
        for (MarketCart cart : marketCarts) {
            Integer number = cart.getNumber();
            BigDecimal price = cart.getPrice();
            sum = sum.add(price.multiply(new BigDecimal(number)));
            totalNum += number;
        }
        cartTotalBean.setGoodsAmount(sum);
        cartTotalBean.setGoodsCount(totalNum);
        // 被选中的  checked = 1 即仍存活的(选中的)。 但是deleted = 0 仍不能忘
        MarketCartExample liveCartExample = new MarketCartExample();
        liveCartExample.createCriteria().andUserIdEqualTo(id).andCheckedEqualTo(true).andDeletedEqualTo(false);
        List<MarketCart> liveCarts = marketCartMapper.selectByExample(liveCartExample);
//        MarketCart[] liveCarts = marketCartMapper.selectByUserIdAndDeleted(id);
        BigDecimal amount = new BigDecimal("0");
        Integer liveNum = 0;
        for (MarketCart liveCart : liveCarts) {
            Integer number = liveCart.getNumber();
            BigDecimal price = liveCart.getPrice();
            amount = amount.add(price.multiply(new BigDecimal(number)));
            liveNum += number;
        }
        cartTotalBean.setCheckedGoodsAmount(amount);
        cartTotalBean.setCheckedGoodsCount(liveNum);
        cartIndexVO.setCartTotal(cartTotalBean);
        // ----------------------------------------------------

        // 现在是 ListBean元素。 所有的都要。
        List<CartIndexVO2.CartListBean> cartListBeans = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (MarketCart marketCart : marketCarts) {
            CartIndexVO2.CartListBean cartListBean = new CartIndexVO2.CartListBean();
            if (marketCart.getAddTime() != null)
                cartListBean.setAddTime(formatter.format(marketCart.getAddTime()));
            if (marketCart.getUpdateTime() != null)
                cartListBean.setUpdateTime(formatter.format(marketCart.getUpdateTime()));
//            cartListBean.setAddTime(marketCart.getAddTime().toString());
//            cartListBean.setUpdateTime(marketCart.getUpdateTime().toString());
            cartListBean.setChecked(marketCart.getChecked());
            cartListBean.setDeleted(marketCart.getDeleted());
            cartListBean.setGoodsName(marketCart.getGoodsName());
            cartListBean.setGoodsSn(marketCart.getGoodsSn());
            cartListBean.setPicUrl(marketCart.getPicUrl());
            cartListBean.setId(marketCart.getId());
            cartListBean.setNumber(marketCart.getNumber());
            cartListBean.setProductId(marketCart.getProductId());
            cartListBean.setSpecifications(marketCart.getSpecifications());
            cartListBean.setUserId(marketCart.getUserId());
            cartListBean.setPrice(marketCart.getPrice());
            cartListBean.setGoodsId(marketCart.getGoodsId());
            cartListBeans.add(cartListBean);
        }
        cartIndexVO.setCartList(cartListBeans);
        return cartIndexVO;
    }

    @Override
    public void updateChecked(CartCheckedBO2 cartCheckedBO, Integer userId) {
        if (userId == null) {
            throw new RuntimeException("请登录后访问。");
        }
        Boolean check = null;
        Integer isChecked = cartCheckedBO.getIsChecked();
        if (isChecked == 1) {
            check = true;
        } else {
            check = false;
        }
        List<Integer> productIds = cartCheckedBO.getProductIds();

        for (Integer productId : productIds) {
            MarketCart marketCart = new MarketCart();
            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andProductIdEqualTo(productId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
            List<MarketCart> carts = marketCartMapper.selectByExample(marketCartExample);
            Integer id = carts.get(0).getId();
            marketCart.setId(id);
            marketCart.setUpdateTime(new Date());
            marketCart.setChecked(check);
            marketCartMapper.updateByPrimaryKeySelective(marketCart);
        }
    }

    @Override
    public void deleteCart(CartDeleteBO2 cartDeleteBO, Integer userId) {
        if (userId == null) {
            throw new RuntimeException("请登录后访问。");
        }
        Boolean deleted = true;
        List<Integer> productIds = cartDeleteBO.getProductIds();
        for (Integer productId : productIds) {
            MarketCart marketCart = new MarketCart();
            MarketCartExample marketCartExample = new MarketCartExample();
            // 拿到了productId 和 user_Id 那么 就可以确定一列主键。  还要确认是未删除的。
            marketCartExample.createCriteria().andProductIdEqualTo(productId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
            List<MarketCart> carts = marketCartMapper.selectByExample(marketCartExample);
            // 获取主键。
            Integer id = carts.get(0).getId();
            marketCart.setId(id);
            marketCart.setUpdateTime(new Date());
            marketCart.setDeleted(deleted); //删除。 置为true即可。
            marketCartMapper.updateByPrimaryKeySelective(marketCart);
        }
    }

    @Override
    public Result updateNum(CartUpdateBO2 cartUpdateBO, Integer userId) {
        if (userId == null) {
            throw new RuntimeException("请登录后访问。");
        }
        Integer id = cartUpdateBO.getId();
        Integer number = cartUpdateBO.getNumber();
        Integer productId = cartUpdateBO.getProductId();
        MarketGoodsProduct marketGoodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
        Integer stocks = marketGoodsProduct.getNumber();
        if (number > stocks) {
            return Result.fail(711, "对不起，添加至购物车的数量大于商家库存:" + stocks + "，请重新选择");
        }
        // 购物车的id已在手里。
        MarketCart marketCart = new MarketCart();
        marketCart.setId(id);
        marketCart.setNumber(number);
        marketCart.setUpdateTime(new Date());
        // 并不改变checked
        // 通过userId 和 goodsId
        marketCartMapper.updateByPrimaryKeySelective(marketCart);
        return Result.ok();
    }

    /**
     * @description:。
     * @param:
     * @return:
     * @author 岳子昂
     * @date: 2022-01-11 22:29
     */
    @Override
    public BigDecimal getPrice(Integer cartId, Integer userId) {
        if (userId == null) {
            throw new RuntimeException("请登录后访问。");
        }
        // 创建BigDecimal对象  用于累加->商品的总价格。
        BigDecimal goodsTotalPrice = new BigDecimal("0");
        List<MarketCart> checkedGoodsList = new ArrayList<>();
        if (cartId == 0) {
            // 通过购物车页面 **下单付款** 调用checkout 则会直接返回cartid=0
            // 意味着默认=> (checked=0且deleted=0时) 就进行返回大数组。
            // 用于选择对象们。
            MarketCartExample cartExample = new MarketCartExample();
            cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false).andCheckedEqualTo(true);

            checkedGoodsList = marketCartMapper.selectByExample(cartExample);

            for (MarketCart cart : checkedGoodsList) {

                goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));

            }

        } else {
            // 就得到一个。 根据主键筛选到的购物车那一行。
            MarketCart cart = marketCartMapper.selectByPrimaryKey(cartId);
            checkedGoodsList.add(cart);
            goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
        }

        return goodsTotalPrice;
    }

    /**
     * @description:
     * @param:
     * @return:
     * @author 岳子昂
     * @date: 2022-01-11 22:29
     */
    @Override
    public List<MarketCart> getGoodIds(Integer cartId, Integer userId) {
        if (userId == null) {
            throw new RuntimeException("请登录后访问。");
        }
// 创建BigDecimal对象  用于累加->商品的总价格。
        BigDecimal goodsTotalPrice = new BigDecimal("0");
        List<MarketCart> checkedGoodsList = new ArrayList<>();
        if (cartId == 0) {
            // 通过购物车页面 **下单付款** 调用checkout 则会直接返回cartid=0
            // 意味着默认=> (checked=0且deleted=0时) 就进行返回大数组。
            // 用于选择对象们。
            MarketCartExample cartExample = new MarketCartExample();
            cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false).andCheckedEqualTo(true);

            checkedGoodsList = marketCartMapper.selectByExample(cartExample);

            for (MarketCart cart : checkedGoodsList) {

                goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));

            }

        } else {
            // 就得到一个。 根据主键筛选到的购物车那一行。
            MarketCart cart = marketCartMapper.selectByPrimaryKey(cartId);
            checkedGoodsList.add(cart);
            goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
        }
        return checkedGoodsList;
    }

    @Override
    // 购物车的处理。  gan
    public CartCheckoutVO2 getCheckoutVO(CartCheckoutBO2 cartCheckoutBO, Integer userId) {
        if (userId == null) {
            throw new RuntimeException("请登录后访问。");
        }
        // 创建BigDecimal对象  用于累加->商品的总价格。
        BigDecimal goodsTotalPrice = new BigDecimal("0");
        List<MarketCart> checkedGoodsList = new ArrayList<>();
        if (cartCheckoutBO.getCartId() == 0) {
            // 通过购物车页面 **下单付款** 调用checkout 则会直接返回cartid=0
            // 意味着默认=> (checked=0且deleted=0时) 就进行返回大数组。
            // 用于选择对象们。
            MarketCartExample cartExample = new MarketCartExample();
            // 选择deleted = 0 且 checked = 1，userid 为 当前对象。-> 未删已选还是本人。
            cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false).andCheckedEqualTo(true);
            List<MarketCart> carts = marketCartMapper.selectByExample(cartExample);
            for (MarketCart cart : carts) {
                // 选中了。
                checkedGoodsList.add(cart);
                goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        } else {
            // 就得到一个。 根据主键筛选到的购物车那一行。
            if (cartCheckoutBO.getCartId() != null && cartCheckoutBO.getCartId() != 0) {
                MarketCart cart = marketCartMapper.selectByPrimaryKey(cartCheckoutBO.getCartId());
                checkedGoodsList.add(cart);
                goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }

        MarketAddress checkedAddress = new MarketAddress();
        // addressId = 0 ->  就输出默认的。（但是没默认的就随便了）
        // 有的话 就是当前选中的addressId ，
        // 没有的话，就是默认。（清楚缓存后首次选。）
        if (cartCheckoutBO.getAddressId() != 0 && cartCheckoutBO.getAddressId() != null) {
            // 不为0，直接根据主键拿就是了。
            checkedAddress = marketAddressMapper.selectByPrimaryKey(cartCheckoutBO.getAddressId());
        } else if (cartCheckoutBO.getAddressId() == 0) {
            MarketAddressExample marketAddressExample = new MarketAddressExample();
            // 当前用户的默认。
            marketAddressExample.createCriteria().andUserIdEqualTo(userId).andIsDefaultEqualTo(true);
            List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);
            if (marketAddresses != null)
                checkedAddress = marketAddresses.get(0);
        }
        // 用于筛选。
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        // 根据market_coupon_user表进行筛选。
        //          ->拿到本人拥有的。 顺便还要判断能不能用。
        couponUserExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        // 该变量表示：本人拥有的优惠券数量。
        Integer availableCouponLength = 0;
        // 本人拥有的。
        List<MarketCouponUser> ownCoupons = marketCouponUserMapper.selectByExample(couponUserExample);
        for (MarketCouponUser ownCoupon : ownCoupons) {
            //status 即：使用状态, 如果是0则未使用；如果是1则已使用；如果是2则已过期；如果是3则已经下架；',
            if (ownCoupon.getStatus() == 0) {
                availableCouponLength++;
            }
        }
        // 我要算钱。商品价格->  -优惠券扣的钱  -> +运费 ->  -团购价格 ->  -积分换算 = 实际结的钱。
        // 默认是-1  0是没有能用的。 -> 判断后根据主键拿couponId 去找表中的作用价值。
        BigDecimal couponPrice = new BigDecimal("0");
        Integer couponId = cartCheckoutBO.getCouponId();
        if (couponId != null && couponId.compareTo(0) == 1) { // compareTo == 1 即大于0的意思。
            MarketCoupon coupon = marketCouponMapper.selectByPrimaryKey(couponId);
            couponPrice = coupon.getDiscount();
        }

        // 不需要就还是0 .
        BigDecimal freightValue = new BigDecimal("0");
        BigDecimal freight_min = new BigDecimal(marketSystemMapper.selectValueByName("market_express_freight_min"));
        if (freight_min.compareTo(goodsTotalPrice) == 1) {
            freightValue = new BigDecimal(marketSystemMapper.selectValueByName("market_express_freight_value"));
        }
        BigDecimal orderTotalPrice = goodsTotalPrice.subtract(couponPrice).add(freightValue);
        // 不考虑团购 积分。，。。。
        BigDecimal actualPrice = orderTotalPrice;
        CartCheckoutVO2 cartCheckoutVO = new CartCheckoutVO2();
//
        cartCheckoutVO.setCartId(cartCheckoutBO.getCartId());
        cartCheckoutVO.setAddressId(cartCheckoutBO.getAddressId());
        cartCheckoutVO.setCouponId(couponId);
        cartCheckoutVO.setUserCouponId(cartCheckoutBO.getUserCouponId());
        cartCheckoutVO.setGrouponRulesId(cartCheckoutBO.getGrouponRulesId());
        cartCheckoutVO.setFreightPrice(freightValue);
        cartCheckoutVO.setActualPrice(actualPrice);
        cartCheckoutVO.setGoodsTotalPrice(goodsTotalPrice);
        // 团队不写了。 写死为0。
        cartCheckoutVO.setGrouponPrice(new BigDecimal(0));
        cartCheckoutVO.setOrderTotalPrice(orderTotalPrice);
        cartCheckoutVO.setCouponPrice(couponPrice);
        cartCheckoutVO.setAvailableCouponLength(availableCouponLength);
        // 购物车赋值
        List<CartCheckoutVO2.CheckedGoodsListBean> cBs = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (MarketCart marketCart : checkedGoodsList) {
            CartCheckoutVO2.CheckedGoodsListBean cB = new CartCheckoutVO2.CheckedGoodsListBean();
            cB.setId(marketCart.getId());
            cB.setChecked(marketCart.getChecked());
            cB.setDeleted(marketCart.getDeleted());
            cB.setGoodsId(marketCart.getGoodsId());
            cB.setGoodsSn(marketCart.getGoodsSn());
            cB.setGoodsName(marketCart.getGoodsName());
            cB.setNumber(marketCart.getNumber());
            cB.setPicUrl(marketCart.getPicUrl());
            cB.setProductId(marketCart.getProductId());
            cB.setSpecifications(marketCart.getSpecifications());
            if (marketCart.getAddTime() != null)
                cB.setAddTime(formatter.format(marketCart.getAddTime()));
            if (marketCart.getUpdateTime() != null)
                cB.setUpdateTime(formatter.format(marketCart.getUpdateTime()));
            cB.setPrice(marketCart.getPrice());
            cB.setUserId(marketCart.getUserId());
            cBs.add(cB);
        }
        cartCheckoutVO.setCheckedGoodsList(cBs);
        // 赋值地址信息
        CartCheckoutVO2.CheckedAddressBean cAB = new CartCheckoutVO2.CheckedAddressBean();
        if (checkedAddress.getAddTime() != null)
            cAB.setAddTime(formatter.format(checkedAddress.getAddTime()));
        if (checkedAddress.getUpdateTime() != null)
            cAB.setUpdateTime(formatter.format(checkedAddress.getUpdateTime()));
        cAB.setAreaCode(checkedAddress.getAreaCode());
        cAB.setAddressDetail(checkedAddress.getAddressDetail());
        cAB.setCounty(checkedAddress.getCounty());
        cAB.setCity(checkedAddress.getCity());
        cAB.setDeleted(checkedAddress.getDeleted());
        cAB.setIsDefault(checkedAddress.getIsDefault());
        cAB.setName(checkedAddress.getName());
        cAB.setId(checkedAddress.getId());
        cAB.setProvince(checkedAddress.getProvince());
        cAB.setTel(checkedAddress.getTel());
        cAB.setUserId(checkedAddress.getUserId());
        cartCheckoutVO.setCheckedAddress(cAB);
        return cartCheckoutVO;
    }


    @Override
    public Result fastAddCart(CartAddBO2 fastAddBO, Integer userId) {
        if (userId == null) {
            throw new RuntimeException("未经登录，无权访问。");
        }
        // 先根据得到的对象进行利用
        // add 的时候  如果数据库表中有deleted =0 且遍历userid的购物车
        //  若productid等于添加的id. 则更新加1，而不是insert
        MarketCartExample marketCartExample = new MarketCartExample();
        // goodsId和productId 足以定商品的唯一属性。  不同规格就insert
        marketCartExample.createCriteria().andProductIdEqualTo(fastAddBO.getProductId()).andGoodsIdEqualTo(fastAddBO.getGoodsId()).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<MarketCart> carts = marketCartMapper.selectByExample(marketCartExample);
        // 购物车中出现两行同一完全一样的商品 ，除非通过数据库自定义添加。
        if (carts.size() == 1) {
            Integer number = fastAddBO.getNumber();
            // 我更新数据，原购物车中数量与这次立即购买的数量保持一致。
            // number += carts.get(0).getNumber();
            // 购物车同种的加即可。
            MarketCart marketCart = new MarketCart();
            // 主键用原来的。
            marketCart.setId(carts.get(0).getId());
            marketCart.setUpdateTime(new Date());
            marketCart.setNumber(number);
            marketCartMapper.updateByPrimaryKeySelective(marketCart);
            return Result.ok(marketCart.getId());
        }

        // 新的数据： 原来没添加过。则通过insert 而非update
        MarketGoodsProduct marketGoodsProduct = goodsProductMapper.selectByPrimaryKey(fastAddBO.getProductId());
        // 库存。
        Integer stocks = marketGoodsProduct.getNumber();
        if (fastAddBO.getNumber() > stocks) {
            return Result.fail(711, "对不起，添加至购物车的数量大于商家库存:" + stocks + "，请重新选择");
        }
        MarketCart marketCart = new MarketCart();// 13个属性值。
        // 目前只是添加至购物车，并不能进入订单表，只能进入订单商品表（即购物车表）
        // 所以对表中的order_id 不予理睬。
        // 获得goodsId,specification,url,number(购买数) 赋值到订单货物表中。
        Integer goodsId = marketGoodsProduct.getGoodsId();
        marketCart.setGoodsId(goodsId); // 13
        marketCart.setPrice(marketGoodsProduct.getPrice());// 2
        String[] specifications = marketGoodsProduct.getSpecifications();
        marketCart.setSpecifications(specifications);// 3
        String url = marketGoodsProduct.getUrl();
        marketCart.setPicUrl(url);// 4
        marketCart.setNumber(fastAddBO.getNumber());// 5
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(fastAddBO.getGoodsId());
        marketCart.setGoodsSn(marketGoods.getGoodsSn());// 6
        marketCart.setGoodsName(marketGoods.getName());// 7
        marketCart.setAddTime(new Date());// 8
        marketCart.setUpdateTime(new Date()); // 9
        marketCart.setUserId(userId);  // 10
        marketCart.setDeleted(false); // 11
        marketCart.setChecked(false); // 12   添加至购物车的时候并未被选哦
        //  marketCart.setUserId();
        marketCart.setProductId(marketGoodsProduct.getId());// 14
        marketCartMapper.insertSelective(marketCart);
        System.out.println(marketCart.getId());
        return Result.ok(marketCart.getId());
    }
}
